package com.candy.candylog.business.controller;

import com.candy.candylog.business.service.IOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author suYanLong
 * @version 1.0
 * @date 2024/5/24 15:22
 * @Description 描述
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("order")
public class OrderController {

    private final IOrderService orderService;

    Lock lock = new ReentrantLock(true);

    @GetMapping("buy")
    public void buy() {
        /**
         * TODO 模拟高并发下单扣减库存场景【正确加锁】
         */
        CountDownLatch latch = new CountDownLatch(100);
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                try {
                    latch.await();
                    lock.lock();
                    try {
                        orderService.buy(1, 2);
                    } catch (Exception e) {
                        throw e;
                    } finally {
                        lock.unlock();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
            latch.countDown();
        }

        /**
         * TODO 模拟高并发下单扣减库存场景【错误加锁】
         */
        CountDownLatch latchError = new CountDownLatch(100);
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                try {
                    latchError.await();
                    orderService.buyError(2, 2);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
            latchError.countDown();
        }
    }

}

